package Song.Han.Demo02;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/*
    文件上传案例的服务器端实现
*/
public class TCPServer {
    public static void main(String[] args) throws IOException {
        System.out.println("服务器启动...");
        //1. 创建服务器端
        ServerSocket server = new ServerSocket(6666);
        while (true) {
            //2. 创建连接
            Socket socket = server.accept();
            new Thread(()-> {
                    try {
                        //3. 创建流对象
                        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
                        //判断文件夹是否存在，否则创建
                        File file = new File("E:\\IDeaProject\\Server");
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        String filename = System.currentTimeMillis()+"证件照copy.png";
                        BufferedOutputStream bosLocal = new BufferedOutputStream(new FileOutputStream(file + "\\"+filename));
                        //4. 使用流对象
                        int len = 0;
                        byte[] bytes = new byte[1024];
                        while ((len = bis.read(bytes)) != -1) {
                            bosLocal.write(bytes, 0, len);
                        }

                        socket.getOutputStream().write("上传成功".getBytes());

                        //5. 关闭资源
                        bosLocal.close();
                        bis.close();
                    }catch (IOException e) {
                        e.printStackTrace();
                    }
            }).start();
        }
    }
}

